<?php
declare (strict_types = 1);

namespace app\api\controller;

use think\Request;
use app\admin\service\TokenServer as TokenServer;
use app\api\model\User as UserModel;

class WxLoginController
{
    public function wxLogin(Request $request){
        //获取code码
        $code = $request->get('code');
        //获取微信授权url
        $url = sprintf(config('wx.url'),config('wx.AppID'),config('wx.AppSecret'),$code);
        //获取openid
        $data = curlGet($url);
        //进行查询数据库里面是否有该用户，如果没有，则进行新增
        $user = UserModel::where('openid',$data['openid'])->find();
        //如果没有用户进行创建
        if (empty($user)){
            $user = UserModel::create([
                'openid'=>$data['openid']
            ]);
        }
        //生成token,保存用户登录状态
        $token = (new TokenServer())->generateToken($user->id);

        return json(['token'=>$token,'error_code'=>0,'msg'=>'登录成功']);
    }

}
